package com.naml.e_syn;

/**
 * @author marin
 * @version 1.0
 * @date 2025/4/26 17:24
 * @desc 使用继承Thread类实现窗口卖票--实现线程同步---synchronized（同步代码块的方式）
 */
@SuppressWarnings("all")
public class ThreadSynSellTicket01 {
    public static void main(String[] args) {
        ThreadSynSellTicket sellTicket01 = new ThreadSynSellTicket();
        ThreadSynSellTicket sellTicket02 = new ThreadSynSellTicket();
        ThreadSynSellTicket sellTicket03 = new ThreadSynSellTicket();
        sellTicket01.start();
        sellTicket02.start();
        sellTicket03.start();
    }
}

@SuppressWarnings("all")
class ThreadSynSellTicket extends Thread {
    //由于继承方式，所以定义static用来多线程共享数据
    private static int count = 100;
    @Override
    public void run() {
        while(true){
            //同步代码块的方式
            synchronized (ThreadSynSellTicket.class){
                if (count <= 0) {
                    break;
                }
                try {
                    Thread.sleep(500);
                    System.out.println("窗口"+Thread.currentThread().getName() +"：卖票，剩余张数："+(--count));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
